package main

import (
	"fmt"
	"log"
	"math/rand"
	"strings"

	"github.com/eatmoreapple/openwechat"
	"github.com/kevwan/chatbot/bot"
	"github.com/kevwan/chatbot/bot/adapters/logic"
	"github.com/kevwan/chatbot/bot/adapters/storage"
	"github.com/skip2/go-qrcode"
)

func ConsoleQrCode(uuid string) {
	q, _ := qrcode.New("https://login.weixin.qq.com/l/"+uuid, qrcode.Low)
	fmt.Println(q.ToString(true))
}

func ask(question string) string {
	store, err := storage.NewSeparatedMemoryStorage("corpus.gob")
	if err != nil {
		log.Fatal(err)
	}
	chatbot := &bot.ChatBot{
		LogicAdapter: logic.NewClosestMatch(store, 5),
	}
	answers := chatbot.GetResponse(question)
	if len(answers) == 0 {
		return "什么意思我没听明白"

	} else if strings.Contains(question, "陈尧") {
		return "陈尧是个大帅逼"
	}
	i := rand.Intn(len(answers))
	return answers[i].Content
}

func GetFriend(self *openwechat.Self, nickName string) *openwechat.Friend {
	friends, _ := self.Friends()
	// for _, friend := range friends {
	// 	fmt.Println(friend.NickName)
	// }
	return friends.GetByNickName(nickName)
}

func main() {
	bot := openwechat.DefaultBot(openwechat.Desktop)
	bot.UUIDCallback = ConsoleQrCode
	bot.ScanCallBack = func(body []byte) { fmt.Println(string(body)) } //扫码回调，扫码后还没登录就可以感知到的信息
	bot.LoginCallBack = func(body []byte) { fmt.Println("登录成功") }      //登录回调，扫码登录后要做的操作

	// // 创建热存储容器对象
	reloadStorage := openwechat.NewJsonFileHotReloadStorage("storage.json")
	// // 执行热登录
	bot.HotLogin(reloadStorage)
	// bot.Login()
	// 注册消息处理函数
	bot.MessageHandler = func(msg *openwechat.Message) {
		// fmt.Println(msg.FromUserName)
		// if msg.IsText() && msg.FromUserName == "@64aec9a8a3f3ff830faa66191d4fd3a2be6bd19fca7357b9ca51d40ae8ed254a" {
		if msg.IsText() {

			msg.ReplyText(ask(msg.Content))
		}
	}

	// self, _ := bot.GetCurrentUser()
	// f := GetFriend(self, "Private")
	// self.SendTextToFriend(f, "我是陪聊机器人，目前有25万语料学习，快来和我对话吧")
	// fmt.Println(f.UserName)

	bot.Block()
}
